package readfiles;
/**
 *
 * @author SUPERSAIYAN20
 */
import java.io.*;
import java.util.Scanner;
public class ReadWriteFiles {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args){
        
        //Doc files
        String s;
        System.out.println("Nhap ten Files can doc: ");
        Scanner input=new Scanner(System.in);
        s=input.nextLine();
        System.out.println(Readfiles(s));
         System.out.println("Nhap vao noi dung can chinh sua: ");
         String text=input.nextLine();
        System.out.println(WriteFiles(s,text,true));
    }
    protected static String Readfiles(String s){
        try {
            FileInputStream fr = new FileInputStream(s);
            Reader r= new java.io.InputStreamReader(fr, "UTF8");
            StringBuilder text;
            try (BufferedReader br = new BufferedReader(r)) {
                text = new StringBuilder();
                String line=null;
                while((line=br.readLine())!=null){
                    text.append(line).append("\n");
                }
            }
            return text.toString();
        }
        catch(Exception e){
            System.out.println("Khong doc duoc file!!! "+s);
        }
        return "";
    }
    protected static boolean WriteFiles(String s ,String text,boolean a){
        String oldFiles="";
        if(!a) oldFiles=Readfiles(s);
        Scanner input1 =new Scanner(System.in);
            System.out.println("Nhap vao file dau ra: ");
            String w=input1.nextLine();
           
        try{
            FileOutputStream fw=new FileOutputStream(w);
            try (Writer wr = new java.io.OutputStreamWriter(fw, "UTF8")) {
                wr.write(oldFiles+text);
            }
            return true;
        }
        catch(Exception e){
            System.out.println("Khong the ghi duoc file!!! "+w);
            return false;
        }
    }
}
